package com.snail.utils;

import com.snail.exception.BusinessException;
import com.snail.exception.ErrorCode;
import com.snail.model.pojo.SysPermission;
import com.snail.model.pojo.SysRolePermission;
import com.snail.model.pojo.SysUserRole;
import com.snail.service.SysPermissionService;
import com.snail.service.SysRolePermissionService;
import com.snail.service.SysUserRoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author 蔡徐坤
 * @Date 2025/7/17 12:31
 * @Description: 权限共用方法工具类
 */

@Component
@RequiredArgsConstructor
public class PermissionHelperUtils {

    private final SysUserRoleService userRoleService;
    private final SysRolePermissionService rolePermissionService;
    private final SysPermissionService permissionService;


    /**
     * 获取用户的所有权限
     */
    public List<SysPermission> getUserPermissions(Long userId) {
        // 1. 查询用户所有角色ID
        List<Long> roleIds = userRoleService.lambdaQuery()
                .eq(SysUserRole::getUserId, userId)
                .list()   //这里是查到的当前登录用户的角色ID集合
                .stream()
                //这里是用stream流调用出.map的方法，将用userId查出来的roleId集合重新放进一个新的Stream<Long>中
                .map(SysUserRole::getRoleId)
                //collect 是结束stream流的方法，并将stream流中的元素收集到一个集合中
                .collect(Collectors.toList());
        // 如果用户没有角色 ,抛出异常
        if (roleIds.isEmpty()) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "用户未分配任何角色");
        }

        // 2. 查询所有角色拥有的权限ID
        List<Long> permissionIds = rolePermissionService.lambdaQuery()
                //查询出来的roId可能有多个，用in方法将对应的权限都查出来
                .in(SysRolePermission::getRoleId, roleIds)
                .list()
                .stream()
                .map(SysRolePermission::getPermissionId)
                .distinct() //有可能有重复的权限ID，这里用distinct方法去重
                .collect(Collectors.toList());

        if (permissionIds.isEmpty()) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "用户没有任何权限");
        }

        // 3. 获取权限实体
        return permissionService.lambdaQuery()
                .in(SysPermission::getId, permissionIds)
                .list();
    }

    /**
     * 获取用户的所有权限码
     */
    public List<String> getUserPermissionCodes(Long userId) {
        List<SysPermission> permissions = getUserPermissions(userId);
        return permissions.stream()
                .map(SysPermission::getCode)  // 获取权限码
                .distinct()
                .collect(Collectors.toList());
    }
}
